package com.webserver.core;

import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理请求环节
 */
public class DispatcherServlet {
    public void service(HttpServletRequest request, HttpServletResponse response){
        String path = request.getUri();
        System.out.println("请求路径:"+path);
        File file = new File("./webapps"+path);
        String line;
        if(file.isFile()){//如果用户请求的是一个文件
            response.setEntity(file);
            String name = file.getName();
            /*
                根据请求的文件的后缀名,设置Content-Type对应的值
                html          text/html
                css           text/css
                js            application/javascript
                png           image/png
                gif           image/gif
                jpg           image/jpeg
             */
            String sub = name.substring(name.lastIndexOf(".")+1);
            Map<String,String> valueMap = new HashMap<>();
            valueMap.put("html","text/html");
            valueMap.put("css","text/css");
            valueMap.put("js","application/javascript");
            valueMap.put("png","image/png");
            valueMap.put("gif","image/gif");
            valueMap.put("jpg","image/jpeg");


            response.putHeader("Content-Type",valueMap.get(sub));
            response.putHeader("Content-Length",String.valueOf(file.length()));

        }else{//否则发送404页面
            response.setStatusCode(404);
            response.setStatusReason("NotFound");
            file = new File("./webapps/root/404.html");
            response.setEntity(file);
            response.putHeader("Content-Type","text/html");
            response.putHeader("Content-Length",String.valueOf(file.length()));
        }
        response.putHeader("server","WebServer");
    }
}
